package com.joshondesign.sdljava.gfx;

import com.joshondesign.sdljava.events.Gestures;
import com.joshondesign.sdljava.events.Keyboard;

public class TextboxNode extends Control {
    int cursor = 0;
    private StringBuffer text = new StringBuffer();

    public TextboxNode() {
        this.width = 200;
        this.height = 100;
        Gestures.listen(Gestures.MouseClick(), new Callback<Gestures.MouseEvent>() {
            public void call(Gestures.MouseEvent mouseEvent) {
                if(inside(mouseEvent.getPoint().getX()
                    ,mouseEvent.getPoint().getY(),
                    x,y,width, height)) {
                    Gestures.requestFocus(TextboxNode.this);
                } else {
                    Gestures.releaseFocus(TextboxNode.this);
                }
            }
        });
        Gestures.listen(Gestures.KeyPressed(), new Callback<Gestures.KeyEvent>() {
            public void call(Gestures.KeyEvent keyEvent) {
                if(Gestures.getFocusedControl() != TextboxNode.this) return;

                if(keyEvent.getKeyCode().isText()) {
                    insertText(cursor, keyEvent.getText());
                    cursor++;
                }
                if(keyEvent.getKeyCode() == Keyboard.Keycode.Backspace) {
                    removeText(cursor, 1);
                    cursor--;
                }
                if(keyEvent.getKeyCode() == Keyboard.Keycode.Left) {
                    if(cursor > 0) cursor--;
                }
                if(keyEvent.getKeyCode() == Keyboard.Keycode.Right) {
                    if(cursor < text.length()) cursor++;
                }
            }
        });
    }

    private void insertText(int cursor, String s) {
        this.text.insert(cursor, s);
    }

    private void removeText(int cursor, int i) {
        //Util.p("cursor = " + cursor + " i = " + i + " length = " + text.length());
        int start = cursor-1;
        int end = cursor-1+i;
        //Util.p("deleting: " + start + " " + end);
        text.delete(start,end);
    }


    @Override
    public void draw(GFX gfx) {
        gfx.setPaint(SColor.WHITE);
        gfx.fillRect(x, y, width, height);
        gfx.setPaint(SColor.BLACK);
        gfx.drawRect(x, y, width, height);
        gfx.drawString(font, text.toString(), 5, 35 + y);

        //only show the cursor when we have the focus
        if(Gestures.getFocusedControl() == this) {
            int cursorX = this.cursor*10;
            if(cursor > 0 && text.length() > 0) {
                GFX.TextMetrics metrics = gfx.measureString(font, text.substring(0,cursor));
                cursorX = metrics.maxx;
            }
            gfx.setPaint(SColor.BLUE);
            gfx.fillRect(cursorX+5+x-3, y + 10, 2, 30);
        }
    }
}
